﻿using System;
using System.Net;
using System.Web.Mvc;
using EPiServer.Community.Blog;
using EPiServer.Find;
using JoelAbrahamsson.BlogExtensions;
using JoelAbrahamsson.Web.ViewModels;
using log4net;

namespace JoelAbrahamsson.Web.Controllers
{
    public class SiteSearchController : Controller
    {
        IClient client;
        private ILog errorLog;

        public SiteSearchController(IClient client, ILog errorLog)
        {
            this.client = client;
            this.errorLog = errorLog;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public RedirectToRouteResult Index(string q)
        {
            return RedirectToAction("Index", new { q });
        }

        public ActionResult Index(string q, int? maxHits)
        {
            if (!maxHits.HasValue)
            {
                maxHits = 10;
            }
            var query = client.Search<Entry>(Language.English)
                .For(q)
                .Select(x => new SearchHit
                                 {
                                     Id = x.ID,
                                     Title = !string.IsNullOrEmpty(x.Title.AsHighlighted(new HighlightSpec { FragmentSize = 100, PreTag = "<strong>", PostTag = "</strong>" })) ? x.Title.AsHighlighted() : x.Title,
                                     Text = x.Content.AsHighlighted(new HighlightSpec { NumberOfFragments = 1, FragmentSize = 300, PreTag = "<strong>", PostTag = "</strong>"})
                                 })
                .Take((short)maxHits.Value);

            var queryResult = query.GetResult();
            foreach (var searchHit in queryResult)
            {
                var entry = BlogHandler.GetEntry(searchHit.Id);
                searchHit.Url = entry.GetUrl(ControllerContext.RequestContext);
                searchHit.Text = !string.IsNullOrEmpty(searchHit.Text) ? searchHit.Text : entry.GetTeaserText();
            }
            var searchResult = SearchResult.Create(queryResult, q, Url.Action("Index", "SiteSearch", new { q, maxHits = maxHits.Value + 10 }));
            if (Request.IsAjaxRequest())
            {
                searchResult.StartFromHitNumber(maxHits.Value - 10);
                return View("SearchResultList", searchResult);
            }
            return View(searchResult);
        }

        private void LogError(WebException exception)
        {
            string logMessage = "Unable to get search result from SiteSeeker service.";
            logMessage += Environment.NewLine;
            logMessage += exception.Message;
            logMessage += Environment.NewLine;
            logMessage += exception.StackTrace;

            errorLog.Error(logMessage);
        }
    }
}
